import { Injectable } from "@nestjs/common";
import { AdministratorEntity } from "./administrator.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import * as svgCaptcha from "svg-captcha";
import { captchaConfig } from "../../config/captcha";
import { calculateHash } from "../../utils/hash";
import { Response } from "express";

@Injectable()
export class AdministratorService {
  constructor(
    @InjectRepository(AdministratorEntity)
    private readonly administratorEntity: Repository<AdministratorEntity>
  ) {}

  /**
   * Generate captcha
   * @param res
   * @param session
   */
  public async generateCaptcha(res: any, session: any): Promise<void> {
    // 1、Generate mathematical expression captcha
    const captcha = svgCaptcha.createMathExpr(
      captchaConfig.captchaCreateMathExprConfig
    )
    // 2、Save the result value of mathematical expression captcha in the session
    session.captcha = captcha.text
    // 3、Return the captcha to the client in image format
    res.type("image/svg+xml").send(captcha.data)
  }

  /**
   * Login
   * @param body
   * @param session
   * @param res
   */
  public async login(body: any, session: any, res: Response): Promise<void> {
    try {
      const { account, password, captcha, email = "", rememberAccount } = body
      // 1、Determine if the captcha is correct
      if (captcha?.toLowerCase() !== session?.captcha?.toLowerCase()) {
        res.json({
          status: "error",
          message: "验证码错误！"
        })
        return
      }
      // 2、Determine if account and password is existed
      const accountData = await this.administratorEntity.find({
        where: [
          {
            id: 1,
            account,
            password: calculateHash(password)
          },
          {
            id: 1,
            email,
            password: calculateHash(password)
          }
        ]
      })
      if (accountData.length === 0) {
        res.json({
          status: "error",
          message: "账号或密码错误！"
        })
        return
      }
      // 3、Open session
      session.cookie.maxAge = rememberAccount === "true" ? 604800000 : 7200000
      session.info = {
        character: "admin"
      }
      // 4、Return information
      res.json({
        status: "success",
        message: "登录成功！"
      })
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * Logout
   * @param session
   * @param res
   */
  public async logout(session: any, res: Response): Promise<void> {
    try {
      // 1、Clear the authentication credentials of the client
      res.clearCookie("cookie")
      // 2、Terminating a session on the server
      session.destroy()
      // 3、Return information
      res.json({
        status: "success",
        message: "成功退出登录！"
      })
    } catch (err) {
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * Modifying account information
   * @param body
   * @param res
   */
  public async updateAccount(body: any, res: any): Promise<void> {
    try {
      const { account, password, email } = body
      await this.administratorEntity.update(1, {
        account,
        password: calculateHash(password),
        email
      })
      res.json({ status: "success", message: "信息修改成功！" })
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * Obtain information
   * @param res
   */
  public async getInfo(res: any): Promise<void> {
    try {
      const result = await this.administratorEntity.findOne({
        where: { id: 1 }
      })
      res.json(result)
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Reset password
   * @param body
   * @param res
   * @param session
   */
  public async reset(body: any, res: any, session: any): Promise<void> {
    try {
      const { email, captcha, password } = body
      if (captcha === session.emailCaptcha) {
        await this.administratorEntity.update(
          { email },
          { password: calculateHash(password) }
        )
        res.json({ status: "success", message: "密码重置成功！" })
      } else {
        res.json({ status: "error", message: "验证码错误！" })
      }
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }
}
